package fr.efrei.abrousserajaspera.common.time;

import java.time.Clock;
import java.time.Instant;
import java.util.LinkedList;

import fr.efrei.abrousserajaspera.common.time.Event;
import fr.efrei.abrousserajaspera.common.time.GameEngineAndQueue;

public class GameEngineAndQueueIP implements GameEngineAndQueue {
	private LinkedList<RegisterEvent> events = new LinkedList<RegisterEvent>();

	// j initialise la liste dans le moteur a l heure actuel
	public GameEngineAndQueueIP(Clock horloge) {
		for (int i = 0; i < events.size(); i++) {
			this.events.get(i).setHorloge(horloge);
		}
	}
	
	public LinkedList<RegisterEvent> getEvents() {
		return events;
	}

	public void setEvents(LinkedList<RegisterEvent> events) {
		this.events = events;
	}

	@Override
	public void update() {
		for (int i = 0; i < events.size(); i++) {
			if (this.getCurrentInstant().equals(Clock.systemUTC().instant())
					|| this.getCurrentInstant().isBefore(
							Clock.systemUTC().instant())) {
				if (this.getCurrentInstant().equals(
						events.get(i).getTrigger().instant())) {
					events.get(i).setTrigger(Clock.systemUTC());
					events.get(i).getEvent().trigger();
					events.removeFirst();
				}
			} else {
				events.get(i).setHorloge(Clock.systemUTC());
				break;
			}
		}
	}

	@Override
	public Instant getCurrentInstant() {
		return events.getFirst().getTrigger().instant();
	}

	@Override
	public void register(Event... event) {
		if (event.length == 0)
			System.out.println("Pas de event a ajouter!");
		else{
			for (int i = 0; i < event.length; i++) {
				events.addFirst(new RegisterEvent(event[i]));
			}
		}
	}

}
